function [f, g, h] = L_etaj(x, model, j)

% global model;
% global j;

x=x';

N     = model.N;
k     = model.k;
k_hat = model.k_hat;


term1 = (-1/(2*model.sigma_02(j)^2))*((x.^2)*(sum((model.sigma_1.^2+model.alpha_1.^2),1))');
term1 = term1*(model.lambda^2);

term2 = 0;
for m=2:k
   for l=1:(m-1)
        term2 = term2 - (1/model.sigma_02(j)^2)*x(l)*x(m)*(model.alpha_1(:,l).*model.alpha_1(:,m));
   end
end
term2 = sum(term2);
term2 = term2*(model.lambda^2);

term3 = (1/model.sigma_02(j)^2)*sum((model.alpha_2(:,j)-model.alpha_02(j)).*(model.alpha_1*x'));
term3 = term3*(model.lambda);

f     = -(term1+term2+term3);


%% specifying the Jacobian

if nargout > 1
    
term11 = ((-1/model.sigma_02(j)^2)*(x.*(sum((model.sigma_1.^2+model.alpha_1.^2),1))))';
term11 = term11*(model.lambda^2);

term12 = zeros(1,k);
for l=1:k
   for m=1:k
       if(m~=l)
        term12(l) = term12(l) - (1/model.sigma_02(j)^2)*x(m)*sum((model.alpha_1(:,l).*model.alpha_1(:,m)));
       end
   end
end

term12 = term12';
term12 = term12*(model.lambda^2);

term13 = (1/model.sigma_02(j)^2)*(model.alpha_1'*(model.alpha_2(:,j)-model.alpha_02(j)));
term13 = term13*(model.lambda);

g      = -(term11+term12+term13)';


%% specifying the Hessian

  if nargout > 2
    
   term21 = (-1/model.sigma_02(j)^2)*sum(model.sigma_1.^2+model.alpha_1.^2,1);
   term21 = term21*(model.lambda^2);
   
   term22 = zeros(k,k);

   for l=1:k
     for m=1:(l-1)
      term22(l,m) = -sum(model.alpha_1(:,l).*model.alpha_1(:,m));
      term22(m,l) = term22(l,m);
     end
   end

   term22 = term22/model.sigma_02(j)^2;
   term22 = term22*(model.lambda^2);
   
   h      = -(diag(term21)+term22);

  end

end


end




